#!/usr/bin/env python2
import os
import sys
import errno
import uuid
import getopt
import subprocess
import time

admin = os.path.abspath(os.path.split(os.path.realpath(__file__))[0] + '/../admin')
sys.path.insert(0, admin)

import socket
hostname = socket.gethostname()
address = socket.gethostbyname(hostname)
__pool_idx__ = 0
__pool_tmp__ = "/tmp/pool_idx"

def _get_value(path):
    size = os.path.getsize(path)
    fd = open(path, 'r')
    buf = fd.read(size)
    fd.close()
    return buf

def _set_value(path, buf):
    if not os.path.exists(os.path.dirname(path)):
        os.makedirs(os.path.dirname(path))
    fd = open(path, 'w')
    fd.write(buf)
    fd.close()

def create_pool_disk(name):
    global __pool_idx__
    idx = __pool_idx__ % 256
    __pool_idx__ = __pool_idx__ + 1
    _set_value(__pool_tmp__, str(__pool_idx__))
    tmp = '/dev/shm/lich4_test.tmp'
    s = str(uuid.uuid1())
    cmd = 'mkdir  /opt/fusionstack/data/tmp &>/dev/null'
    os.system(cmd)
    cmd = 'bash -c "echo -n \'cluster=xxxx;node=lich_testx;type=new;disk=1;pool=%s;cache=0;cached=0;\' > %s"' % (name, tmp)
    os.system(cmd)
    cmd = 'bash -c "dd if=%s of=/opt/fusionstack/data/tmp/%u.file bs=1 seek=1612 &>/dev/null"' % (tmp, idx)
    os.system(cmd)
    cmd = 'truncate  /opt/fusionstack/data/tmp/%u.file --size 10G' % (idx)
    os.system(cmd)
    cmd = 'ln -s /opt/fusionstack/data/tmp/%u.file /opt/fusionstack/data/disk/disk/%u.disk' % (idx, idx)
    os.system(cmd)

def create_pool(target, disk_count):
    for i in range(disk_count):
        create_pool_disk(target)

    os.system("/opt/fusionstack/lich/libexec/lichbd pool create %s" % (target))
    
def create_cluster():
    os.system('pkill -9 lichd')
    os.system('pkill -9 lich.inspect')
    os.system('pkill -9 redis-server')
    os.system('rm -rf /opt/fusionstack/data')
    os.system('rm -rf /opt/fusionstack/log/')
    os.system('rm -rf /opt/fusionstack/etc/cluster.conf')
    os.system('rm -rf /dev/shm/lich4')
    os.system('rm -rf /tmp/core')
    os.system('mkdir -p /tmp/core')
    os.system('mkdir -p /opt/fusionstack/data/')
    os.system('mkdir -p /opt/fusionstack/etc/')
    os.system('mkdir -p /opt/fusionstack/tmp/')
    os.system('mkdir -p /opt/fusionstack/data/disk/disk')
    os.system('mkdir -p /opt/fusionstack/data/disk/tier')
    os.system('systemctl stop etcd')
    os.system('rm -rf /opt/fusionstack/data/etcd/')

    os.system('touch  /opt/fusionstack/data/fake')
    os.system('echo 3 > /proc/sys/vm/drop_caches')
    os.system('echo 0 > %s' % (__pool_tmp__))

    os.system('cp ../etc/lich.conf.solo /opt/fusionstack/etc/lich.conf')
    os.system("sed -i 's/127.0.0.0/%s/g' /opt/fusionstack/etc/lich.conf" % (address))
    os.system("sed -i 's/#clustername XXX/clustername testcluster/g' /opt/fusionstack/etc/lich.conf")
    os.system('/opt/fusionstack/lich/bin/lich create %s' % (hostname))
    
    global __pool_idx__
    __pool_idx__ = int(_get_value(__pool_tmp__))

    target = "pool1"
    create_pool(target, 5)
    
def usage():
    print ("usage:")
    print ("" + sys.argv[0] + " --createcluster")
    print ("" + sys.argv[0] + " --test")

    
def main():
    test = False
    conf = False
    create = False

    try:
        opts, args = getopt.getopt(
            sys.argv[1:],
            'hv', ['createcluster', 'test']
            )
    except getopt.GetoptError, err:
        print str(err)
        usage()
        exit(errno.EINVAL)

    for o, a in opts:
        if o in ('--help'):
            usage()
            exit(0)
        elif o == '--test':
            test = True
        elif o == '--createcluster':
            create = True
        else:
            usage()
            exit(errno.EINVAL)

    if (test):
        print "test"
    elif (create):
        print "createcluster"
        create_cluster()
    else:
        pass

if __name__ == '__main__':
    if (len(sys.argv) == 1):
        usage()
    else:
        main()
